import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import lightgbm as lgb
from sklearn.metrics import mean_squared_error

# 读取数据（假设数据文件名为 sales_data.csv）
df = pd.read_csv('lilylikes-all-LO2312019AXNHS.csv', low_memory=False, encoding='GBK')

# 日期格式转换
df['date_id'] = pd.to_datetime(df['date_id'], format='%Y%m%d')
df['first_new_date'] = pd.to_datetime(df['first_new_date'], format='%Y/%m/%d')

# 计算product_age
df['product_age'] = (df['date_id'] - df['first_new_date']).dt.days

# 检查并处理负天数
df = df[df['product_age'] >= 0]



# 选择特征列（排除日期列）
features = ['product_code', 'middle_class_name', 'product_age']
target = 'sale_qty'
# 转换类别类型
df[['product_code', 'middle_class_name']] = df[['product_code', 'middle_class_name']].astype('category')
# 提取特征和标签
X = df[features]
y = df[target]



# 按日期排序
df = df.sort_values('date_id')
# 按时间划分数据集（80%训练，20%测试）
split_idx = int(len(df) * 0.8)
X_train, y_train = X.iloc[:split_idx], y.iloc[:split_idx]
X_test, y_test = X.iloc[split_idx:], y.iloc[split_idx:]


# 定义类别特征列名
categorical_features = ['product_code', 'middle_class_name']

# 创建Dataset
train_data = lgb.Dataset(
    X_train,
    label=y_train,
    categorical_feature=categorical_features,
    free_raw_data=False
)


params = {
    'objective': 'regression',
    'metric': 'rmse',
    'num_leaves': 31,
    'learning_rate': 0.05,
    'feature_fraction': 0.9,
    'bagging_fraction': 0.8,
    'bagging_freq': 5,
    'verbose': -1
}

# 训练模型
model = lgb.train(
    params,
    train_data,
    num_boost_round=1000,
    valid_sets=[lgb.Dataset(X_test, y_test)]
)




# 生成预测结果
y_pred = model.predict(X_test, num_iteration=model.best_iteration)

# 计算RMSE
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
print(f'Test RMSE: {rmse:.2f}')

# 查看特征重要性
print(lgb.plot_importance(model, height=0.8, figsize=(10, 6)))